import { formatDate } from '../../../utils/util';

Page({
  data: {
    // 地图数据
    longitude: 112.93,  // 默认经度
    latitude: 27.75,    // 默认纬度
    markers: [] as any[],
    
    // 表单数据
    startLocation: '城关镇汽车站东50米',
    endLocation: '新化县洋溪镇新化南站',
    passengers: 1,
    phone: '',
    notes: '',
    
    // 选项数据
    carTypes: ['不限', '出租车', '其他'],
    selectedCarType: '不限',
    timeTypes: ['实时', '预约'],
    selectedTimeType: '实时',
    pickupTypes: ['司机来接', '站点等待'],
    selectedPickupType: '司机来接',
    depositOptions: ['1元', '5元', '10元', '20元'],
    depositIndex: 0,
    
    // 日期时间选择器
    dateTimeArray: [] as any[],
    dateTimeIndex: [0, 0, 0, 0, 0],
    appointmentTime: '',
    appointmentTimeText: '',
  },

  onLoad() {
    // 初始化日期时间选择器
    this.initDateTimePicker();
    
    // 获取当前位置
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        const { longitude, latitude } = res;
        this.setData({
          longitude,
          latitude,
          markers: [{
            id: 1,
            longitude,
            latitude,
            width: 20,
            height: 20,
            callout: {
              content: '当前位置',
              color: '#ffffff',
              fontSize: 10,
              borderRadius: 4,
              bgColor: '#3b82f6',
              padding: 4,
              display: 'ALWAYS'
            }
          }]
        });
      }
    });
  },
  
  initDateTimePicker() {
    const date = new Date();
    const years = [];
    const months = [];
    const days = [];
    const hours = [];
    const minutes = [];
    
    // 未来两年
    for (let i = date.getFullYear(); i <= date.getFullYear() + 1; i++) {
      years.push(`${i}年`);
    }
    
    // 月份
    for (let i = 1; i <= 12; i++) {
      months.push(`${i < 10 ? '0' + i : i}月`);
    }
    
    // 天
    for (let i = 1; i <= 31; i++) {
      days.push(`${i < 10 ? '0' + i : i}日`);
    }
    
    // 小时
    for (let i = 0; i < 24; i++) {
      hours.push(`${i < 10 ? '0' + i : i}时`);
    }
    
    // 分钟
    for (let i = 0; i < 60; i += 5) {
      minutes.push(`${i < 10 ? '0' + i : i}分`);
    }
    
    this.setData({
      dateTimeArray: [years, months, days, hours, minutes]
    });
  },
  
  onDepositChange(e: any) {
    this.setData({ depositIndex: e.detail.value });
  },

  // 监听输入变化
  onStartLocationChange(e: any) {
    this.setData({ startLocation: e.detail.value });
  },
  
  onEndLocationChange(e: any) {
    this.setData({ endLocation: e.detail.value });
  },
  
  onPhoneChange(e: any) {
    this.setData({ phone: e.detail.value });
  },
  
  onNotesChange(e: any) {
    this.setData({ notes: e.detail.value });
  },
  
  // 设置乘客数量
  setPassengers(e: any) {
    this.setData({ passengers: e.currentTarget.dataset.num });
  },
  
  // 设置车型
  setCarType(e: any) {
    this.setData({ selectedCarType: e.currentTarget.dataset.type });
  },
  
  // 设置用车时间类型
  handleTimeTypeChange(e: any) {
    const timeType = e.detail.value;

    console.log('timeType:', e.detail.value);
    
    this.setData({ 
      selectedTimeType: timeType,
      appointmentTime: timeType === '实时' ? '' : this.data.appointmentTime,
      appointmentTimeText: timeType === '实时' ? '' : this.data.appointmentTimeText
    });
  },
  
  // 设置接车方式
  setPickupType(e: any) {
    this.setData({ selectedPickupType: e.currentTarget.dataset.type });
  },
  
  // 日期时间选择器变化
  onDateTimeChange(e: any) {
    const { dateTimeArray } = this.data;
    const { value } = e.detail;
    
    const year = parseInt(dateTimeArray[0][value[0]]);
    const month = parseInt(dateTimeArray[1][value[1]]);
    const day = parseInt(dateTimeArray[2][value[2]]);
    const hour = parseInt(dateTimeArray[3][value[3]]);
    const minute = parseInt(dateTimeArray[4][value[4]]);
    
    const dateObj = new Date(year, month - 1, day, hour, minute);
    const isoString = dateObj.toISOString();
    const formattedDateTime = formatDate(dateObj, 'yyyy-MM-dd HH:mm');
    
    this.setData({
      dateTimeIndex: value,
      appointmentTime: isoString,
      appointmentTimeText: formattedDateTime
    });
  },
  
  onColumnChange(e: any) {
    const { column, value } = e.detail;
    const { dateTimeIndex, dateTimeArray } = this.data;
    
    // 更新选中的索引
    dateTimeIndex[column] = value;
    
    // 当年份或月份变化时，需要调整天数
    if (column === 0 || column === 1) {
      const year = parseInt(dateTimeArray[0][dateTimeIndex[0]]);
      const month = parseInt(dateTimeArray[1][dateTimeIndex[1]]);
      
      const daysInMonth = new Date(year, month, 0).getDate();
      const days = [];
      
      for (let i = 1; i <= daysInMonth; i++) {
        days.push(`${i < 10 ? '0' + i : i}日`);
      }
      
      dateTimeArray[2] = days;
      
      // 如果当前选中的日期超出了新月份的最大天数，则调整为最大天数
      if (dateTimeIndex[2] >= days.length) {
        dateTimeIndex[2] = days.length - 1;
      }
    }
    
    this.setData({ dateTimeIndex, dateTimeArray });
  },
  
  // 返回上一页
  goBack() {
    wx.navigateBack();
  },
  
  // 提交订单
  submitOrder() {
    const {
      startLocation,
      endLocation,
      passengers,
      phone,
      notes,
      selectedCarType,
      selectedTimeType,
      appointmentTime,
      selectedPickupType
    } = this.data;
    
    // 表单验证
    if (!startLocation) {
      return wx.showToast({ title: '请输入上车地点', icon: 'none' });
    }
    
    if (!endLocation) {
      return wx.showToast({ title: '请输入目的地', icon: 'none' });
    }
    
    if (!phone) {
      return wx.showToast({ title: '请输入手机号', icon: 'none' });
    }
    
    if (!/^1\d{10}$/.test(phone)) {
      return wx.showToast({ title: '请输入有效的手机号', icon: 'none' });
    }
    
    if (selectedTimeType === '预约' && !appointmentTime) {
      return wx.showToast({ title: '请选择预约时间', icon: 'none' });
    }
    
    // 构建订单数据
    const orderData = {
      startLocation,
      endLocation,
      passengers,
      phone,
      notes,
      carType: selectedCarType,
      timeType: selectedTimeType,
      appointmentTime: selectedTimeType === '预约' ? appointmentTime : '',
      pickupType: selectedTimeType === '预约' ? selectedPickupType : ''
    };
    
    // 显示提交中
    wx.showLoading({ title: '提交中...' });
    
    // TODO: 调用API提交订单
    console.log('提交订单数据:', orderData);
    
    // 模拟API调用
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({ title: '订单提交成功', icon: 'success' });
      
      // 返回上一页或跳转到订单详情页
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }, 1500);
  }
});
